<template>
  <div class="app-container">
    <el-card title="库存数据可视化">
      <!-- 分类导航区域 -->
      <div class="category-nav">
        <!-- 可以用el-tree或el-select实现分类选择 -->
        <el-tree
          :data="categoryTree"
          :props="treeProps"
          node-key="id"
          default-expand-all
          @node-click="handleNodeClick"
          style="margin-bottom: 20px;"
        />
      </div>

      <!-- 图表展示区域 -->
      <div class="charts-container">
        <!-- 库存数量图表 -->
        <el-card class="chart-card">
          <div slot="header" class="chart-title">
            <span>{{ currentCategory ? currentCategory + ' 库存数量' : '请选择分类查看库存数据' }}</span>
          </div>
          <div ref="inventoryChart" class="chart" />
        </el-card>

        <!-- 库存占比图表 -->
        <el-card class="chart-card">
          <div slot="header" class="chart-title">
            <span>{{ currentCategory ? currentCategory + ' 库存占比' : '请选择分类查看库存占比' }}</span>
          </div>
          <div ref="proportionChart" class="chart" />
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import warn from '@/api/warn/warn'
import * as echarts from 'echarts'
import resize from '../dashboard/mixins/resize'

export default {
  name: 'InventoryChart',
  mixins: [resize],
  data() {
    return {
      categoryTree: [],
      currentCategory: '',
      currentCategoryData: {},
      treeProps: {
        label: 'categoryName',
        children: 'children'
      },
      inventoryChart: null,
      proportionChart: null
    }
  },
  created() {
    this.loadCategoryTree()
  },
  mounted() {
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  beforeDestroy() {
    if (this.inventoryChart) {
      this.inventoryChart.dispose()
    }
    if (this.proportionChart) {
      this.proportionChart.dispose()
    }
  },
  methods: {
    // 加载分类树数据
    loadCategoryTree() {
      warn.getCategoryTree().then(response => {
        this.categoryTree = this.transformData(response.data)
      })
    },

    // 处理分类节点点击事件
    handleNodeClick(data) {
      this.currentCategory = data.categoryName
      this.currentCategoryData = data
      this.updateCharts()
    },

    // 初始化图表
    initCharts() {
      this.inventoryChart = echarts.init(this.$refs.inventoryChart)
      this.proportionChart = echarts.init(this.$refs.proportionChart)
    },

    // 更新图表数据
    updateCharts() {
      // 处理数据，提取商品和库存信息
      const productData = this.extractProductData(this.currentCategoryData)

      // 更新库存数量图表
      this.updateInventoryChart(productData)

      // 更新库存占比图表
      this.updateProportionChart(productData)
    },

    // 提取商品数据
    extractProductData(categoryData) {
      // 这里需要递归遍历分类下的所有商品
      const products = []

      // 处理分类下的直接商品
      if (categoryData.products && categoryData.products.length > 0) {
        categoryData.products.forEach(product => {
          products.push({
            name: product.productName,
            quantity: product.quantity || 0,
            threshold: product.warningThreshold || 0
          })
        })
      }

      // 递归处理子分类
      if (categoryData.children && categoryData.children.length > 0) {
        categoryData.children.forEach(child => {
          if (!child.isProduct) { // 确保是分类节点而不是商品节点
            const childProducts = this.extractProductData(child)
            products.push(...childProducts)
          }
        })
      }

      return products
    },

    // 更新库存数量图表
    updateInventoryChart(products) {
      const names = products.map(item => item.name)
      const quantities = products.map(item => item.quantity)
      const thresholds = products.map(item => item.threshold)

      this.inventoryChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function(params) {
            // 自定义tooltip格式，显示库存/阈值的百分比
            const dataIndex = params[0].dataIndex
            const quantity = params[0].value
            const threshold = thresholds[dataIndex]
            const percentage = threshold > 0 ? (quantity / threshold * 100).toFixed(1) : '0.0'

            let status = ''
            if (percentage >= 100) {
              status = '<span style="color:red;">(超出阈值)</span>'
            } else if (percentage >= 95) {
              status = '<span style="color:#e6a23c;">(接近阈值)</span>'
            } else {
              status = '<span style="color:#67c23a;">(正常)</span>'
            }

            return params[0].name + '<br/>'
              + params[0].marker + params[0].seriesName + ': ' + params[0].value + ' ' + status + '<br/>'
              + params[1].marker + params[1].seriesName + ': ' + params[1].value + '<br/>'
              + '占比: ' + percentage + '%'
          }
        },
        legend: {
          data: ['当前库存', '预警阈值']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: names,
          axisLabel: {
            interval: 0,
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '数量'
        },
        series: [
          {
            name: '当前库存',
            type: 'bar',
            data: quantities,
            itemStyle: {
              // 根据库存与阈值的比例动态设置颜色
              color: function(params) {
                const quantity = params.value
                const threshold = thresholds[params.dataIndex]

                // 处理阈值为0的情况
                if (threshold <= 0) {
                  return '#67C23A' // 默认绿色
                }

                const ratio = quantity / threshold

                if (ratio > 1) {
                  return '#F56C6C' // 超出阈值 - 红色
                } else if (ratio >= 0.95) {
                  return '#E6A23C' // 达到95%阈值 - 黄色
                } else {
                  return '#67C23A' // 正常 - 绿色
                }
              }
            }
          },
          {
            name: '预警阈值',
            type: 'line',
            data: thresholds,
            itemStyle: {
              color: '#909399'
            },
            // 添加阈值线的样式
            lineStyle: {
              type: 'dashed'
            },
            // 显示阈值点的标签
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          }
        ]
      })
    },

    // 更新库存占比图表
    updateProportionChart(products) {
      const pieData = products.map(item => ({
        name: item.name,
        value: item.quantity
      })).filter(item => item.value > 0) // 过滤掉库存为0的商品

      this.proportionChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: pieData.map(item => item.name)
        },
        series: [
          {
            name: '库存占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      })
    },

    // 转换数据格式，与warn/index.vue中的方法保持一致
    transformData(nodes) {
      return nodes.map(node => {
        const transformedNode = {
          ...node,
          id: node.categoryId
        };

        const productNodes = node.products.map(product => ({
          id: `product_${product.productId}`,
          categoryName: product.productName,
          sku: product.sku,
          productId: product.productId,
          alertStatus: product.alertStatus,
          warningThreshold: product.warningThreshold,
          quantity: product.quantity,
          children: [],
          isProduct: true
        }));

        transformedNode.children = [
          ...(node.children ? this.transformData(node.children) : []),
          ...productNodes
        ];
        return transformedNode;
      });
    }
  }
}
</script>

<style scoped lang="scss">
.category-nav {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 20px;
}

.charts-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.chart-card {
  flex: 1;
  min-width: 400px;
}

.chart-title {
  font-weight: bold;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>
